using System.Collections.Generic;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TFS.Kanban.Domain;
using TFS.Kanban.Domain.Services;

namespace TFS.Kanban.VS2010.Services
{
    public class IterationService : IIterationService
    {
        private readonly ProjectService _projectService;

        public IterationService(IProjectService projectService)
        {
            _projectService = (ProjectService)projectService;
        }

        public IEnumerable<IIteration> GetIterations(IProject project)
        {
            var iterations = new HashSet<IIteration>();
            var tfsProject = _projectService.GetTfsProject(project.Id);

            foreach (Node iterationNode in tfsProject.IterationRootNodes)
            {
                var iteration = new Iteration { Id = iterationNode.Id, Name = iterationNode.Name, Path = iterationNode.Path, Areas = new HashSet<IArea>() };
                if (iterationNode.HasChildNodes) iteration.Areas = GetArea(iterationNode.ChildNodes);

                iterations.Add(iteration);
            }

            return iterations;
        }

        private static IEnumerable<IArea> GetArea(NodeCollection childNodes)
        {
            var areas = new HashSet<IArea>();

            foreach (Node areaNode in childNodes)
            {
                areas.Add(new Area { Id = areaNode.Id, Name = areaNode.Name, Path = areaNode.Path });
            }

            return areas;
        }
    }
}